package com.eshop.web.controllers.websocket;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.eshop.service.mongodb.EOrderService;
import com.eshop.service.mongodb.EUserService;

public class UserLinkHandler implements WebSocketHandler {

	@Autowired
	private EOrderService eorderService;

	@Autowired
	private EUserService euserService;

	/*
	 * @Override protected void handleTextMessage(WebSocketSession session,
	 * TextMessage message) throws Exception { super.handleTextMessage(session,
	 * message); TextMessage returnMessage = new
	 * TextMessage(message.getPayload()+" received at server");
	 * session.sendMessage(returnMessage); }
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session)
			throws Exception {
		// TODO Auto-generated method stub
	}

	@Override
	public void handleMessage(WebSocketSession session,
			WebSocketMessage<?> message) throws Exception {
		// TODO Auto-generated method stub
		// Set<String> keys =attr.keySet();
		// Iterator<String> iter = keys.iterator();
		// while(iter.hasNext()){
		// System.out.println("handleMessage:"+attr.get(iter.next()));
		// }
		Object mess = message.getPayload();
		if (mess instanceof String) {
//			 System.out.println(mess.toString());
			// EUser u = new EUser();
			// u.setUsername(mess.toString());
			// EUser euser = euserService.getByUserName(u);
			// System.out.println(euser.getShopName());
			session.sendMessage(new TextMessage("heartbeat".getBytes()));
			UserSessionCache.setMerchantSession((String) mess, session);
		}
	}

	@Override
	public void handleTransportError(WebSocketSession session,
			Throwable exception) throws Exception {
		// TODO Auto-generated method stub
		ChannelPool.removeChannelByChannel(session);
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session,
			CloseStatus closeStatus) throws Exception {
		// TODO Auto-generated method stub
		ChannelPool.removeChannelByChannel(session);
	}

	@Override
	public boolean supportsPartialMessages() {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * 通知商户来订单了
	 * 
	 * @param userId
	 * @param orderId
	 * @throws IOException
	 */
	public void sendOrderToShopper(String userId, String orderId)
			throws IOException {
		ClientInfo client = UserSessionCache.merchantSession.get(userId);
		// System.out.println("老子要发订单啦！！！！");
		if (client == null) {
			System.out.println("商户未登录，没有建立session......请稍等！");
		} else {
			// System.out.println("ready......Go!");
			// String message = "orderId="+orderId;
			// System.out.println(orderId);
			client.getWebSocketSession().sendMessage(
					new TextMessage(orderId.getBytes()));
		}
	}

}